<template>
  <div class="device-list">
    <div class="page-header">
      <h2>设备管理</h2>
      <el-button type="primary" @click="showAddDialog">添加设备</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="设备名称">
          <el-input v-model="searchForm.name" placeholder="请输入设备名称" clearable />
        </el-form-item>
        
        <el-form-item label="设备类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable>
            <el-option label="闸机" value="gate" />
            <el-option label="门锁" value="lock" />
            <el-option label="摄像头" value="camera" />
            <el-option label="传感器" value="sensor" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="在线" value="online" />
            <el-option label="离线" value="offline" />
            <el-option label="故障" value="error" />
            <el-option label="维护" value="maintenance" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="所属场馆">
          <el-select v-model="searchForm.venueId" placeholder="请选择" clearable>
            <el-option label="体育馆" value="1" />
            <el-option label="游泳馆" value="2" />
            <el-option label="篮球场" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 设备列表表格 -->
    <el-card>
      <el-table :data="deviceList" v-loading="loading" border>
        <el-table-column prop="id" label="设备ID" width="80" />
        <el-table-column prop="name" label="设备名称" width="150" />
        <el-table-column prop="type" label="设备类型" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.type === 'gate'" type="primary">闸机</el-tag>
            <el-tag v-else-if="row.type === 'lock'" type="success">门锁</el-tag>
            <el-tag v-else-if="row.type === 'camera'" type="warning">摄像头</el-tag>
            <el-tag v-else-if="row.type === 'sensor'" type="info">传感器</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deviceId" label="设备编号" width="150" />
        <el-table-column prop="venueName" label="所属场馆" width="120" />
        <el-table-column prop="location" label="安装位置" width="150" />
        <el-table-column prop="status" label="设备状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 'online'" type="success">在线</el-tag>
            <el-tag v-else-if="row.status === 'offline'" type="info">离线</el-tag>
            <el-tag v-else-if="row.status === 'error'" type="danger">故障</el-tag>
            <el-tag v-else-if="row.status === 'maintenance'" type="warning">维护</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastOnline" label="最后在线" width="160" />
        <el-table-column prop="createdAt" label="添加时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="editDevice(row)">编辑</el-button>
            <el-button type="info" link @click="viewLogs(row)">日志</el-button>
            <el-button 
              v-if="row.status === 'online'" 
              type="warning" 
              link 
              @click="controlDevice(row, 'restart')"
            >
              重启
            </el-button>
            <el-button type="danger" link @click="deleteDevice(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑设备对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogMode === 'add' ? '添加设备' : '编辑设备'" 
      width="600px"
    >
      <el-form :model="deviceForm" :rules="formRules" ref="deviceFormRef" label-width="100px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="deviceForm.name" placeholder="请输入设备名称" />
        </el-form-item>
        
        <el-form-item label="设备类型" prop="type">
          <el-select v-model="deviceForm.type" placeholder="请选择设备类型">
            <el-option label="闸机" value="gate" />
            <el-option label="门锁" value="lock" />
            <el-option label="摄像头" value="camera" />
            <el-option label="传感器" value="sensor" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="设备编号" prop="deviceId">
          <el-input v-model="deviceForm.deviceId" placeholder="请输入设备编号" />
        </el-form-item>
        
        <el-form-item label="所属场馆" prop="venueId">
          <el-select v-model="deviceForm.venueId" placeholder="请选择场馆">
            <el-option label="体育馆" value="1" />
            <el-option label="游泳馆" value="2" />
            <el-option label="篮球场" value="3" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="安装位置" prop="location">
          <el-input v-model="deviceForm.location" placeholder="请输入安装位置" />
        </el-form-item>
        
        <el-form-item label="设备描述">
          <el-input 
            v-model="deviceForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入设备描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 设备日志对话框 -->
    <el-dialog v-model="logDialogVisible" title="设备日志" width="800px">
      <el-table :data="deviceLogs" max-height="400">
        <el-table-column prop="time" label="时间" width="160" />
        <el-table-column prop="level" label="级别" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.level === 'info'" type="primary">信息</el-tag>
            <el-tag v-else-if="row.level === 'warning'" type="warning">警告</el-tag>
            <el-tag v-else-if="row.level === 'error'" type="danger">错误</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="message" label="日志内容" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'DeviceList',
  setup() {
    const loading = ref(false)
    const dialogVisible = ref(false)
    const logDialogVisible = ref(false)
    const dialogMode = ref('add')
    const deviceFormRef = ref(null)
    
    // 搜索表单
    const searchForm = reactive({
      name: '',
      type: '',
      status: '',
      venueId: ''
    })
    
    // 分页
    const pagination = reactive({
      page: 1,
      size: 10,
      total: 0
    })
    
    // 设备表单
    const deviceForm = reactive({
      name: '',
      type: '',
      deviceId: '',
      venueId: '',
      location: '',
      description: ''
    })
    
    // 表单验证规则
    const formRules = {
      name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
      type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
      deviceId: [{ required: true, message: '请输入设备编号', trigger: 'blur' }],
      venueId: [{ required: true, message: '请选择所属场馆', trigger: 'change' }],
      location: [{ required: true, message: '请输入安装位置', trigger: 'blur' }]
    }
    
    // 设备列表
    const deviceList = ref([
      {
        id: 1,
        name: '主入口闸机',
        type: 'gate',
        deviceId: 'GATE001',
        venueName: '体育馆',
        location: '主入口',
        status: 'online',
        lastOnline: '2024-01-15 16:30:00',
        createdAt: '2024-01-01 10:00:00'
      },
      {
        id: 2,
        name: '更衣室门锁',
        type: 'lock',
        deviceId: 'LOCK001',
        venueName: '体育馆',
        location: '男更衣室',
        status: 'offline',
        lastOnline: '2024-01-15 14:20:00',
        createdAt: '2024-01-01 10:30:00'
      }
    ])
    
    // 设备日志
    const deviceLogs = ref([
      {
        time: '2024-01-15 16:30:00',
        level: 'info',
        message: '设备正常运行'
      },
      {
        time: '2024-01-15 14:20:00',
        level: 'warning',
        message: '设备连接不稳定'
      }
    ])
    
    // 加载数据
    const loadData = async () => {
      loading.value = true
      try {
        // 这里调用API加载设备列表
        console.log('加载设备列表数据')
        pagination.total = deviceList.value.length
      } catch (error) {
        ElMessage.error('加载数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      pagination.page = 1
      loadData()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.assign(searchForm, {
        name: '',
        type: '',
        status: '',
        venueId: ''
      })
      loadData()
    }
    
    // 显示添加对话框
    const showAddDialog = () => {
      dialogMode.value = 'add'
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑设备
    const editDevice = (device) => {
      dialogMode.value = 'edit'
      Object.assign(deviceForm, device)
      dialogVisible.value = true
    }
    
    // 重置表单
    const resetForm = () => {
      Object.assign(deviceForm, {
        name: '',
        type: '',
        deviceId: '',
        venueId: '',
        location: '',
        description: ''
      })
      deviceFormRef.value?.clearValidate()
    }
    
    // 提交表单
    const submitForm = async () => {
      try {
        await deviceFormRef.value.validate()
        
        if (dialogMode.value === 'add') {
          // 这里调用添加API
          ElMessage.success('设备添加成功')
        } else {
          // 这里调用编辑API
          ElMessage.success('设备更新成功')
        }
        
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.log('表单验证失败')
      }
    }
    
    // 删除设备
    const deleteDevice = async (device) => {
      try {
        await ElMessageBox.confirm('确认要删除这个设备吗？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        // 这里调用删除API
        ElMessage.success('设备删除成功')
        loadData()
      } catch (error) {
        console.log('取消删除')
      }
    }
    
    // 控制设备
    const controlDevice = async (device, action) => {
      try {
        // 这里调用设备控制API
        ElMessage.success(`设备${action}命令已发送`)
      } catch (error) {
        ElMessage.error('操作失败')
      }
    }
    
    // 查看日志
    const viewLogs = (device) => {
      // 这里加载设备日志
      logDialogVisible.value = true
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pagination.size = size
      loadData()
    }
    
    const handleCurrentChange = (page) => {
      pagination.page = page
      loadData()
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      loading,
      searchForm,
      pagination,
      deviceList,
      deviceLogs,
      dialogVisible,
      logDialogVisible,
      dialogMode,
      deviceForm,
      formRules,
      deviceFormRef,
      handleSearch,
      resetSearch,
      showAddDialog,
      editDevice,
      submitForm,
      deleteDevice,
      controlDevice,
      viewLogs,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style lang="scss" scoped>
.device-list {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  h2 {
    color: var(--text-color-primary);
    font-weight: 500;
  }
}

.search-card {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style> 